<template>
  <div class="home" @keydown.enter="sendByKeyBord">
    <el-container>
      <el-container>
        <el-header>
          <div>
            <img class="headimg" :src="talkToImg" alt="" />
            <p>{{ withWho }}</p>
          </div>
        </el-header>
        <el-main>
          <div class="homeMain">
            <div
              :style="{ height: chatBoxH, position: 'relative', top: chatBoxT }"
            >
              <div v-for="(v, i) in talkDetailArr" :key="i">
                <div
                  :style="{ display: 'inline-block', width: '500px' }"
                  v-if="v.who"
                >
                  <img
                    :src="talkToImg"
                    alt=""
                    :style="{
                      width: '30px',
                      height: '30px',
                      verticalAlign: 'middle',
                    }"
                  />&nbsp;&nbsp;<span>{{ v.time }}</span
                  ><br />
                  &nbsp;&nbsp;
                  <p
                    :style="{
                      backgroundColor: 'bisque',
                      display: 'inline-block',
                      height: '20px',
                      padding: '10px',
                      lineHeight: '20px',
                      borderRadius: '10px',
                    }"
                  >
                    {{ v.content }}
                  </p>
                </div>
                <div
                  :style="{
                    display: 'inline-block',
                    position: 'relative',
                    left: '710px',
                    width: '500px',
                  }"
                  v-if="v.towho"
                >
                  <img
                    :src="talkImg"
                    alt=""
                    :style="{ width: '30px', height: '30px', float: 'right' }"
                  /><span :style="{ float: 'right', marginTop: '7px' }"
                    >{{ v.time }}&nbsp;&nbsp;</span
                  ><br />
                  &nbsp;&nbsp;
                  <p
                    :style="{
                      backgroundColor: 'bisque',
                      display: 'inline-block',
                      height: '20px',
                      padding: '10px',
                      lineHeight: '20px',
                      borderRadius: '10px',
                      float: 'right',
                      marginTop: '28px',
                      marginRight: '-150px',
                    }"
                  >
                    {{ v.content }}
                  </p>
                </div>
              </div>
            </div>
          </div>
          <div class="homeInp">
            <el-input placeholder="请输入内容" v-model="input" clearable>
            </el-input>
            <el-button type="info" plain @click="sendMassage"
              >发送信息</el-button
            >
          </div>
        </el-main>
      </el-container>
      <el-aside width="200px" class="clearfix">
        <!-- <div class="avatar">
                    <img :src="avatarUrl" alt="上传的图片" v-on:click="openFileInput">
                    <input type="file" ref="fileInput" style="display: none" accept="image/*" v-on:change="uploadImage">
                </div>
                <p>My</p> -->
        <p :style="{ margin: '10px 0px 0 40px' }">好友列表</p>
        <div class="friendAvatar">
          <ul>
            <li
              @click="pathNormal(v.name, i)"
              v-for="(v, i) in friendArr"
              :key="i"
              :style="{
                margin: '10px 0px 10px -20px',
                backgroundColor: 'rgba(255,255,255,0.2) ',
                border: v.active ? 'red 2px solid' : '',
                padding: '5px 10px',
                width: '140px',
                borderRadius: '10px',
              }"
            >
              <img :src="v.img" alt="" :style="{ verticalAlign: 'middle' }" />
              <span> {{ v.name }}</span
              >&nbsp;
              <span
                :style="{
                  color: 'gray',
                  float: 'right',
                  position: 'relative',
                  top: '7.5px',
                }"
                @click="path(v.name, i)"
                >置顶</span
              >
            </li>
          </ul>
        </div>
      </el-aside>
    </el-container>
  </div>
</template>
<script>
import axios from "axios";
export default {
  data() {
    return {
      input: "",
      avatarUrl: "http://localhost:8080/img/fruit.4c5567fb.webp",
      friendArr: [],
      talkDetailArr: [],
      talkId: 0,
      withWho: "",
      hhhh: "sddddd",
      talkToId: -1,
      talkToImg: "",
      talkImg: "",
      chatBoxH: "800px",
      chatBoxT: "0px",
      allData: {},
      yourself: "",
      talkToiddd: 0,
      massageCount: 0,
      loadTalkInterva() {},
      massageCountOffline: 0,
      toLocalChat:[
        {time:'no'}
      ]
    };
  },
  methods: {
    openFileInput() {
      this.$refs.fileInput.click();
    },
    uploadImage(event) {
      const file = event.target.files[0];
      const reader = new FileReader();
      reader.onload = () => {
        this.avatarUrl = reader.result;
      };
      reader.readAsDataURL(file);
    },
    path(name, i) {
        this.withWho = name;
        this.changetalk(i);
    },
    pathNormal(name, i) {
      if (event.target.onabort) {
      this.withWho = name;
      this.changetalkNormal(i);
      return
      }
      if (event.target.style.color != "gray") {
      this.withWho = name;
      this.changetalkNormal(i);
      }
    },
    changetalk(i) {
      this.talkToImg = this.friendArr[i].img;
      let me = this.friendArr[i];
      this.friendArr.splice(i, 1);
      delete me.active;
      this.friendArr.unshift(me);
      let arr=[];
      this.friendArr.forEach((v)=>{
        arr.push(v.id)
      })
      axios.patch('/dbdata/userTalk/'+this.talkId+'',{order:arr})
    },
    changetalkNormal(i) {
      this.talkToId = this.friendArr[i].name;
      this.talkToiddd = this.friendArr[i].id;
      this.talkToImg = this.friendArr[i].img;
      delete this.friendArr[i].active;
      this.loadTalk();
    },
    loadTalk() {
      axios({
        url: "/dbdata/userTalkDetail/" + this.talkId + "",
      }).then(({ data }) => {
        this.talkDetailArr = data.talkDetail;
        this.allData = data;
        let arrTalk = [];
        this.talkDetailArr.forEach((v) => {
          if (v.who == this.talkToId && v.who != "备忘录") {
            arrTalk.push(v);
          }
        });
        data.response.forEach((v) => {
          if (v.towho == this.talkToId) {
            arrTalk.push(v);
          }
        });
        this.talkDetailArr = arrTalk;
        console.log(this.talkDetailArr);
        this.talkDetailArr.sort((a, b) =>
          this.timeToNumber(a.time) > this.timeToNumber(b.time) ? 1 : -1
        );
        this.chatBoxH = this.talkDetailArr.length * 100 + "px";
        if(this.talkDetailArr.length && this.toLocalChat[this.toLocalChat.length-1].time!=this.talkDetailArr[this.talkDetailArr.length-1].time){
          this.chatBoxT = (0-(this.talkDetailArr.length * 100 - 540)) + "px";
          console.log(this.chatBoxT);
          this.toLocalChat=this.talkDetailArr
        }
        if (this.massageCount.length <= data.talkDetail.length) {
          for (
            let i = this.massageCount.length;
            i < data.talkDetail.length;
            i++
          ) {
            this.friendArr.forEach((v) => {
              if (
                data.talkDetail[i].who == v.name &&
                data.talkDetail[i].who != this.talkToId
              ) {
                v.active = "1";
              }
            });
          }
          this.massageCountOffline = data.talkDetail.length;
        }
        if (this.massageCountOffline < data.talkDetail.length) {
          for (
            let i = this.massageCountOffline;
            i < data.talkDetail.length;
            i++
          ) {
            this.friendArr.forEach((v) => {
              if (
                data.talkDetail[i].who == v.name &&
                data.talkDetail[i].who != this.talkToId
              ) {
                v.active = "1";
              }
            });
          }
          this.massageCountOffline = data.talkDetail.length;
          sessionStorage.setItem('massageOffline',this.massageCountOffline)
        }
        this.massageCount = data.talkDetail;
      });
    },
    timeToNumber(time) {
      let n1 = time.split(" ");
      let n2 = n1[0].split("/");
      let n3 = n1[1].split(":");
      let n4 = "";
      let n5 = "";
      n2.forEach((v) => {
        n4 += v;
      });
      n3.forEach((v) => {
        n5 += v;
      });
      return Number(n4 + n5);
    },
    mouseWheel() {
      if (
        event.wheelDelta < 0 &&
        500 - Number(this.chatBoxH.split("p")[0]) <
          Number(this.chatBoxT.split("p")[0])
      ) {
        this.chatBoxT =
          Number(this.chatBoxT.split("p")[0]) + event.wheelDelta + "px";
      }
      if (event.wheelDelta > 0 && Number(this.chatBoxT.split("p")[0]) < 0) {
        this.chatBoxT =
          Number(this.chatBoxT.split("p")[0]) + event.wheelDelta / 2 + "px";
      }
    },
    nowtime() {
      let nowDate = new Date();
      let date2 = {
        year: nowDate.getFullYear(),
        month:
          nowDate.getMonth() + 1 < 10
            ? "0" + (nowDate.getMonth() + 1)
            : nowDate.getMonth() + 1,
        date:
          nowDate.getDate() < 10 ? "0" + nowDate.getDate() : nowDate.getDate(),
        hour:
          nowDate.getHours() < 10
            ? "0" + nowDate.getHours()
            : nowDate.getHours(),
        min:
          nowDate.getMinutes() < 10
            ? "0" + nowDate.getMinutes()
            : nowDate.getMinutes(),
        sec:
          nowDate.getSeconds() < 10
            ? "0" + nowDate.getSeconds()
            : nowDate.getSeconds(),
      };
      let date3 =
        date2.year +
        "/" +
        date2.month +
        "/" +
        date2.date +
        " " +
        date2.hour +
        ":" +
        date2.min +
        ":" +
        date2.sec;
      return date3;
    },
    sendByKeyBord() {
      this.sendMassage();
    },
    sendMassage() {
      if (this.input == "") {
        return;
      }
      this.allData.response.push({
        time: this.nowtime(),
        towho: this.withWho,
        content: this.input,
      });
      axios
        .put("/dbdata/userTalkDetail/" + this.talkId + "", this.allData)
        .then(() => {
          axios({
            url: "/dbdata/userTalkDetail/" + this.talkToiddd + "",
          }).then(({ data }) => {
            this.allData = data;
            this.allData.talkDetail.push({
              time: this.nowtime(),
              who: this.withWho == "备忘录" ? "备忘录" : this.yourself,
              content: this.input,
            });
            axios
              .put(
                "/dbdata/userTalkDetail/" + this.talkToiddd + "",
                this.allData
              )
              .then(() => {
                console.log("发送成功");
                this.input = "";
                this.loadTalk();
              });
          });
        });
    },
  },
  destroyed() {
    console.log("聊天页面注销",this.massageCountOffline);
    clearInterval(this.loadTalkInterval);
    axios.patch("/dbdata/userTalk/" + this.talkId + "", {
      massageCount: this.massageCountOffline,
    });
  },
  mounted() {
    document
      .querySelector(".homeMain")
      .addEventListener("mousewheel", this.mouseWheel);
    this.talkId = sessionStorage.getItem("userId");
    this.talkToiddd = sessionStorage.getItem("userId");
    this.massageCountOffline=sessionStorage.getItem('massageOffline')
    axios({
      url: "/dbdata/userTalk",
    }).then(({ data }) => {
       data.forEach((v) => {
        this.friendArr.push({ id: v.id, img: v.avatar, name: v.name });
      });
      this.yourself = this.friendArr[this.talkId - 1].name;
      this.friendArr[this.talkId - 1].name = "备忘录";
      this.withWho = this.friendArr[this.talkId - 1].name;
      this.talkImg = this.friendArr[this.talkId - 1].img;
      let arrOrder=[]
      data[this.talkId-1].order.forEach((v,i)=>{
        this.friendArr.forEach((h,j)=>{
          if(h.id==v){
            arrOrder.push(h)
          }
        })
      })
      this.friendArr=arrOrder;
  
      this.pathNormal(this.friendArr[0].name, 0)
      this.loadTalk();
    })
    this.loadTalkInterval = setInterval(this.loadTalk, 8 * 1000);
  },
};
</script>
<style scoped lang="less">
.clearfix::after {
  content: "";
  display: block;
  clear: both;
}

.el-container {
  height: 93vh;
  overflow: hidden;
}

.el-header {
  background-color:  #f0f3de;
  color: #333;
  text-align: left;
  line-height: 50px;

  .headimg {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    float: left;
  }

  p {
    margin-left: 50px;
  }
}

.el-aside {
  background-color: rgb(252, 244, 223);
  color: #333;
  text-align: left;

  .avatar {
    img {
      width: 72px;
      height: 72px;
      border-radius: 50%;
      margin: 15px;
      float: left;
      margin-right: 30px;
    }
  }

  p {
    font-size: 28px;
    font-weight: 500;
    margin-top: 40px;
  }

  .friendAvatar {
    margin: 20px;
    text-align: left;
    margin-top: 30px;

    ul {
      padding-left: 20px;

      li {
        list-style: none;
        margin-top: 20px;
        padding-top: 20px;
        &:hover {
          background-color: rgba(255, 255, 255, 0.534) !important;
          cursor: pointer;
        }

        img {
          width: 40px;
          height: 40px;
          border-radius: 50%;
        }
      }
    }
  }
}

.el-main {
  background-color: #f9fbec;
  color: #333;
  text-align: left;

  .homeMain {
    background-color: #fff;
    border: 3px solid #aaa;
    height: 80%;
    width: 95%;
    padding: 20px;
    overflow: hidden;
  }

  .homeInp {
    margin-top: 15px;

    .el-input {
      width: 92%;
      margin-left: 0px;
    }
  }
}

body > .el-container {
  margin-bottom: 40px;
}

.el-container:nth-child(5) .el-aside,
.el-container:nth-child(6) .el-aside {
  line-height: 260px;
}

.el-container:nth-child(7) .el-aside {
  line-height: 320px;
}
</style>
